package com.tian.controller;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.tian.annotation.LoginCheckAnnotation;
import com.tian.dto.WxPrePayReqDto;
import com.tian.enums.ResultCode;
import com.tian.service.PayService;
import com.tian.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年05月12日 15:57
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 * <p>
 * 微信支付
 */
@Slf4j
@RestController
@RequestMapping(value = "/pay")
public class PayController {

    @Resource
    private PayService payService;

    /**
     * 生成预支付单
     */
    @PostMapping("/prePay")
    @LoginCheckAnnotation
    public CommonResult<WxPayMpOrderResult> prePay(HttpServletRequest request, @RequestBody WxPrePayReqDto wxPrePayReqDto) {
        if (wxPrePayReqDto == null || wxPrePayReqDto.getUserId() == null || wxPrePayReqDto.getAmount() == null) {
            return CommonResult.failed(ResultCode.PARAMETER_EMPTY);
        }
        return payService.prePay(wxPrePayReqDto, request);
    }

    /**
     * 支付后台通知
     */
    @PostMapping("/wx/notify")
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            return payService.payNotify(request, response);
        } catch (Exception e) {
            log.error("会带通知失败，异常信息：", e);
            return "回调异常";
        }
    }
}
